import base from './base';
import React from 'react';
import * as mobx from 'mobx';
import * as ForwardPage from './forwardPage';
import * as FormUtil from './formUtil';
import { Bubble } from 'weaver-mobile';
import { _ } from './pcPublic';
import jQuery from 'jQuery';
import * as VariableKeys from '../constants/variableKey';
import * as FormBtnUtil from './formBtnUtil';
// import * as MonitorUtil from './MonitorUtil';
import * as SignUtil from './SignUtil';
import { getPageTitle } from './formUtil';
import { getLabel, showConfirm } from './common';
import PDFSignConfirm from "./../components/prompt/PDFSignConfirm"
import {closeQYSAuth} from "./secondAuthUtil";

let emClient = null;

const emJsApis = [
    'showBottomToolBar', 'hideBottomToolBar',
    'configNavigation', 'resetNavigation', 'previewImage',
    'handleWriting', 'chooseImage', 'getLocalImgData',
    'editImage', 'getLocationList', 'getAudioRecord', 'openLocation',
    'speechTotext', 'userInteractionEnabled', 'userInteractionDisabled',
    "fileSign", "getFileFormatCanSign", "getFlowHandwrite", "saveFlowHandwrite",
    "deleteFlowHandwrite","closeWindow"
];
/**
 * 表单加载校验当前版本支持哪些API，存variableMap
 * @param {校验的API数组} apis
 */
export const verifyEmSDK = () => {
    if (!window.em) return;
    const updateParams = {};
    const params = { 'jsApiList': emJsApis };
    params.success = (args = {}) => {
        let result = args;
        if (typeof args === 'string') result = JSON.parse(args);
        const { checkResult = {} } = result;
        emJsApis.map((k) => {
            updateParams[`em_${k}`] = checkResult[k] || false;
            if (k === "getFileFormatCanSign" && checkResult[k]) {
                getFileFormatCanSign();
            }
        })
        base.wfGlobalStore.batchControlVariableMap(updateParams);
    };
    //同步接口
    window.em.checkJsApi(params);
    emClient = window.em;
}
export { emClient }

/**
 * 判断em指定接口是否可以使用
 * @param {API名称} apiname
 * @return true:支持 false 不支持
 */
export const judgeApiSupport = (apiname) => {
    const { variableMap } = base.wfGlobalStore;
    return window.em && variableMap.has(`em_${apiname}`) && variableMap.get(`em_${apiname}`);
}

//控制底部按钮（表单中）
export const controlBottomBtn = (nextPathname = '', operator) => {//在一些点击事件上执行这个方法
    const { controlVariableMap } =  base.allStores.wfSignInputStore;
    if ((nextPathname === '/req' || (nextPathname === '/req/intervenor' && operator)) && judgeApiSupport('showBottomToolBar')) {
        let btns = FormBtnUtil.getEmBottomBtns();
        // if (nextPathname === '/req/intervenor') {
        //     btns = MonitorUtil.getEmBottomBtns();
        // }
        if (btns.length === 0) return;
        let emBtnParams = {
            'items': btns,
            'success': (argument) => {
                controlVariableMap("isShowEmBottomBtn",true)
                console.log('controlShowBottomBtn-success', argument, emBtnParams);
            },
            'fail': (argument) => {
                console.log('controlShowBottomBtn-fail', argument)
            }
        };
        emClient.hideBottomToolBar({
            'success': (arg) => {
                controlVariableMap("isShowEmBottomBtn",false)
                console.log('controlHideBottomToolBar-success', arg);
            }
        });
        emClient.showBottomToolBar(emBtnParams);
    }
}

//保存手写签批痕迹
export const saveFlowHandwrite = (workflowid) => {
    //客户端说em.checkJsApi("xxx")这种方式是判断jem.js是否支持的，em.chekcJsApi({jsApiList:[],success:(){}})这种方式是判断app是否支持的
    if(judgeApiSupport("saveFlowHandwrite") && emClient.checkJsApi("saveFlowHandwrite")){
        emClient.saveFlowHandwrite({
            workflowid:workflowid,
            success: function (res) {
                console && console.log("保存手写签批痕迹",res)
            }
        });
    }else{
        console && console.log("em不支持saveFlowHandwrite")
    }
}

//获取手写签批痕迹
export const getFlowHandwrite = (workflowid) => {
    if(judgeApiSupport("getFlowHandwrite") && emClient.checkJsApi("getFlowHandwrite")){
        emClient.getFlowHandwrite({
            workflowid: workflowid,
            success: function (argument) {
                let result = getEmResultData(argument);
                const { localExist  = false } = result;
                const { controlVariableMap } =  base.allStores.wfSignInputStore;
                controlVariableMap("localExist",localExist)
                console && console.log("获取手写签批痕迹",localExist)
            }
        });
    }else {
        console && console.log("em不支持getFlowHandwrite")
    }
}

//删除本地流程签批
export const deleteFlowHandwrite = (workflowid) => { 
    if(judgeApiSupport("deleteFlowHandwrite") && emClient.checkJsApi("deleteFlowHandwrite")){
        emClient.deleteFlowHandwrite({
            workflowid:workflowid,
            success: function (res) {
                console && console.log("删除本地流程签批",res)
            }
        });
    }else {
        console && console.log("em不支持deleteFlowHandwrite")
    }
}

//手写签批
export const handleWriting = (inherit=false) => {
    const { saveSignAnnex, isForwad, variableMap, controlVariableMap } = base.allStores.wfSignInputStore;
    const handlewritingKey = isForwad ? VariableKeys.FORWARD_SIGN_HANDWRITTEN : VariableKeys.SIGN_HANDWRITTEN;
    if(judgeApiSupport("handleWriting")){
        emClient.handleWriting({
            'inherit': inherit,
            'success': (argument) => {
                let result = getEmResultData(argument);
                const { localData = '' } = result;
                if(localData){
                    saveSignAnnex(3, localData);
                    controlVariableMap("localExist",true)
                }else{
                   variableMap.delete(handlewritingKey)
                   controlVariableMap("localExist",false)
                }
            },
            'fail': (argument) => {
                console.log('handleWriting-fail', argument)
            }
        })
    }else {
        console.log("em不支持handleWriting")
    }
}

export const continueSpeech = () => {
    emClient.continueSpeech({
        'changeVoice':
            arg => {
                //音量变化回调  int 0-100 一般在50左右
                console.log('changeVoice')
            },
        'continueSpeechend': arg => {
            //{"result":"今天天气怎样？","errMsg":"服务正常","clientType":"iPhone","errCode":0},"handlerName":"continueSpeechend"}
            //语音识别结束 为对象result为识别后的文字 调用一次
        },
        'onContinueSpeech': arg => {
            //{"result":"喂喂","errMsg":"onContinueSpeech:ok","clientType":"iPhone","errCode":0}
            //识别过程中，持续识别，多次调用，同个会话中，后面解析的文字，将会追加在之前的一起返回
        },
        'success':
            arg => {
                //方法 成功响应
            },
        'fail': arg => {
            //识别出错
        },
        'cancel': arg => {

        },
        'complete': arg => {
            //完成
        }
    })
}


export const confirmSignType = (flag, docid, fileName, viewAttr, isannexupload_edit, isFJ, fieldStore) => {
    const { variableMap } = base.wfOperateStore;
    let mobilePDFSign = variableMap.has("mobilePDFSign") ? variableMap.get("mobilePDFSign") : 1;
    if ((fileName.split(".")[1] == "pdf" || fileName.split(".")[1] == "PDF") && (mobilePDFSign == 3 && viewAttr > 1 && isannexupload_edit)) {
        showConfirm({
            title: '请选择签批后的保存方式：',
            content: <PDFSignConfirm />,
            cancelText: getLabel(201, '取消'),
            okText: getLabel(826, '确定'),
            okEvent: () => {
                fileSign(flag, docid, fileName, isFJ,viewAttr, isannexupload_edit, fieldStore);
            },
            cancelEvent:()=>{
                let PDFSign_radioChecked = base.wfGlobalStore.variableMap.has("PDFSign_radioChecked") ? base.wfGlobalStore.variableMap.get("PDFSign_radioChecked") : 0;
                PDFSign_radioChecked==1 && base.wfGlobalStore.controlVariableMap("PDFSign_radioChecked", 0 );
            }
        });
    } else {
        fileSign(flag, docid, fileName, isFJ, viewAttr, isannexupload_edit,fieldStore);
    }
}


//文档签批
export const fileSign = (flag, docid, fileName, isFJ, viewAttr, isannexupload_edit,fieldStore) => {
    const { variableMap } = base.wfGlobalStore;
    const { commonParam } = base.wfGlobalStore;
    const { requestid, authStr, authSignatureStr, f_weaver_belongto_userid, f_weaver_belongto_usertype } = commonParam;

    //是否替换原文件条件准备
    let mobilePDFSign = base.wfOperateStore.variableMap.has("mobilePDFSign") ? base.wfOperateStore.variableMap.get("mobilePDFSign") : "1";
    let PDFSign_radioChecked = variableMap.has("PDFSign_radioChecked") ? variableMap.get("PDFSign_radioChecked") : 0;
    //文档上传下载路径封装
    const imagefileId = (variableMap.has(`imagefiledId_${flag}`) && (fileName.split(".")[1] != "pdf" || fileName.split(".")[1] != "PDF")) ? variableMap.get(`imagefiledId_${flag}`) : flag;
    let url = `/weaver/weaver.file.FileDownload?fileid=${imagefileId}&download=1&`;
    url += `requestid=${requestid}&authStr=${authStr}&authSignatureStr=${authSignatureStr}&f_weaver_belongto_userid=${f_weaver_belongto_userid}&f_weaver_belongto_usertype=${f_weaver_belongto_usertype}`;
    let versionDetail = encodeURI("移动签批")
    let uploadurl = "/api/doc/upload/upload2ReplaceDoc?versionDetail=" + versionDetail + "&docid=" + docid;
    if (isFJ) {
        uploadurl += "&imagefileId=" + imagefileId;
    }
    let isNewDoc = (mobilePDFSign == 1 || (mobilePDFSign == 3 && viewAttr == 1 && isannexupload_edit) || (mobilePDFSign == 3 && PDFSign_radioChecked == 1) );
    if ((fileName.split(".")[1] == "pdf" || fileName.split(".")[1] == "PDF") && isNewDoc) {
        uploadurl += "&newDoc=1";//newDoc=1，生成新版本放在签字意见中，不替换
    }
    //执行签批
    if (judgeApiSupport('fileSign')) {
        emClient.fileSign({
            fileDownloadUrl: url,//文档下载地址
            fileUploadUrl: uploadurl,//保存并上传地址
            fileName: fileName,
            success: function (res) {
                // 返回结果
                if (typeof res == "string") res = JSON.parse(res);
                if (fileName.split(".")[1] == "pdf" || fileName.split(".")[1] == "PDF") {//pdf签批
                    if(mobilePDFSign==3 && viewAttr == 1 && isannexupload_edit){//字段只读且可以上传签字意见附件
                        fileAddToSignAnnex(res, fileName);
                    }else if (mobilePDFSign == 1 || (mobilePDFSign == 3 && PDFSign_radioChecked == 1)) {//pdf签批写入流转意见
                        fileAddToSignAnnex(res, fileName);
                        PDFSign_radioChecked==1 && base.wfGlobalStore.controlVariableMap("PDFSign_radioChecked", 0 );
                    } else if (mobilePDFSign == 2 || (mobilePDFSign == 3 && PDFSign_radioChecked == 0)) {//pdf签批替换原文件
                        replaceDeaultFile(res, flag,fieldStore,docid);
                    }
                } else {
                    replaceDeaultFile(res, flag, fieldStore,docid);
                }
            }
        });
    }
}

//签批替换原文件
const replaceDeaultFile = (res, flag, fieldStore,docid) => {
    const { odocInfo = {} } = base.wfLayoutStore;
    const { imagefileId : odocInfo_imagefileId = "", mobileInfo={} } = odocInfo;
    const { isShowDocTab,addressUrl="" }=mobileInfo;
    const { imagefileId } = res;
    base.wfGlobalStore.batchControlVariableMap({ [`imagefiledId_${flag}`]: imagefileId });
    if(fieldStore){
        let {datas}=fieldStore;
        datas.map(item=>{
            if(item.fileid == docid){
                const{imagefileid:oldImagefileid}=item;
                item.filelink = item.filelink.replace(oldImagefileid,imagefileId);
                item.loadlink = item.loadlink.replace(oldImagefileid,imagefileId);
                item.imagefileid = imagefileId;
            }
        })
        fieldStore.setState({datas:datas})
    }
    //有正文的情况,且签批的是正文，还要更新正文tab下src
    if((odocInfo_imagefileId != imagefileId) && isShowDocTab && !_.isEmpty(odocInfo) && flag == odocInfo_imagefileId ){
        base.wfGlobalStore.controlVariableMap("wf-odocSrc",addressUrl.replace(odocInfo_imagefileId,imagefileId));
    }
}

// pdf签批写入流转意见
const fileAddToSignAnnex = (res, fileName) => {
    const { wfSignInputStore } = base.allStores;
    const { isForwad, controlVariableMap } = wfSignInputStore;
    const annexdocinfoKey = isForwad ? VariableKeys.FORWARD_SIGN_ANNEX_DOC_INFOS : VariableKeys.SIGN_ANNEX_DOC_INFOS;
    const filedatas = SignUtil.getVariableMapVal(annexdocinfoKey, []) || [];
    filedatas.push({
        fileid: res.docId,
        filename: fileName,
        filesize: "",
    })
    controlVariableMap(annexdocinfoKey, filedatas);
}

//是否显示签批按钮的权限判断
export const checkShowSignBtn = (fileExtendName,viewAttr,isannexupload_edit) => {
    if (fileExtendName && fileExtendName.includes(".")) fileExtendName = fileExtendName.split(".")[1];
    if(fileExtendName != "pdf"){
        return true;
    }
    let show=false;
    const { variableMap } = base.wfOperateStore;
    let mobilePDFSign = variableMap.has("mobilePDFSign") ? variableMap.get("mobilePDFSign") : "0";
    /**
        A、写入流转意见
        B、替换原文件
        C、由用户自己选择
        三、再根据权限判断是否显示签批按钮及签批模式
        1、配置二选择A，如果用户没有意见附件上传权限，则不显示签批按钮
        2、配置二选择B，如果用户没有字段编辑权限，则不显示签批按钮
        3、配置二选择C：
        如果有字段编辑权限viewAttr，没有意见附件上传权限isannexupload_edit，则只能是替换，不弹出选择；
        如果无字段编辑权限，有意见附件上传权限，则只能附加到意见，不弹出选择；
        既有字段编辑权限，又有意见附件上传权限时，才弹出选择，由用户选择是替换还是附加；
        两个权限都没有，不能签批。
    */
    if(mobilePDFSign == 1 && isannexupload_edit){//写入流转意见
        show=true;
    }else if(mobilePDFSign == 2 && viewAttr > 1){//替换原文件
        show=true;
    }else if(mobilePDFSign == 3 && (viewAttr > 1 || isannexupload_edit)){//由用户自己选择
        show=true;
    }
    return show;
}

//获取当前file中的loadlink中的参数,并改变参数中的fileid;
export const changeFileid = (file) => {
    const { variableMap } = base.wfGlobalStore;
    const { commonParam } = base.wfGlobalStore;
    const { wfSignInputStore } = base.allStores;
    const { requestid, authStr, authSignatureStr, f_weaver_belongto_userid, f_weaver_belongto_usertype } = commonParam;
    const imagefileId = variableMap.has(`imagefiledId_${file.imagefileid}`) ? variableMap.get(`imagefiledId_${file.imagefileid}`) : file.imagefileid;
    if (imagefileId != file.imagefileid) {
        file.loadlink = changeURLArg(file.loadlink, "fileid", imagefileId);
    }
}

/* 
* url 目标url 
* arg 需要替换的参数名称 
* arg_val 替换后的参数的值 
* return url 参数替换后的url 
*/
export const changeURLArg = (url, arg, arg_val) => {
    let pattern = arg + '=([^&]*)';
    let replaceText = arg + '=' + arg_val;
    if (url.match(pattern)) {
        let tmp = '/(' + arg + '=)([^&]*)/gi';
        tmp = url.replace(eval(tmp), replaceText);
        return tmp;
    } else {
        if (url.match('[\?]')) {
            return url + '&' + replaceText;
        } else {
            return url + '?' + replaceText;
        }
    }
}

//判断是否可以有【签批】按钮
/**
 * @right:当前用户拥有的权限
 * @SuffixName:文件后缀名
 */
export const checkSigningBatch = (right, SuffixName) => {
    const { variableMap } = base.wfGlobalStore;
    const filetype_list = variableMap.get("QP_formatList") || [];
    if (SuffixName && SuffixName.includes(".")) SuffixName = SuffixName.split(".")[1];
    right = SuffixName !== "pdf" ? right : true;
    if (filetype_list && filetype_list.length > 0 && filetype_list.includes(SuffixName) && right) {
        return true;
    } else {
        return false;
    }
}


//获取支持文件签批的格式
export const getFileFormatCanSign = () => {
    emClient.getFileFormatCanSign({
        success: function (res) {
            // 返回结果
            if (typeof res === "string") {
                res = JSON.parse(res);
            }
            const { formatList, errCode } = res;
            if (errCode == 0) {
                base.wfGlobalStore.batchControlVariableMap({ QP_formatList: formatList });
            }
        }
    });
}

//拍照
export const takePhoto = () => {
    emClient.chooseImage({
        'success': (argument) => {
            console.log('chooseImage-success', argument);
            let result = getEmResultData(argument);
            const { localIds = [] } = result;
            if (localIds.length > 0) {
                emClient.getLocalImgData({
                    'localId': localIds[0],
                    'success': (arg) => {
                        console.log(arg);
                    }
                })
            }
        },
        'fail': (argument) => {
            console.log('chooseImage-fail', argument);
        },
        'sourceType': ['camera']
    })
}

//全文批注
export const editImage = () => {
    const { hiddenSignInput, showSignInput, saveSignAnnex, isForwad, fowardSubmitParams,setForwardParams, resetKeyValue} = base.allStores.wfSignInputStore;
    const { hideContinuationProcessBar, continuationProcessInfo, resetContinuationProcessInfo } = base.allStores.wfGlobalStore;
    const forwardVisiable = SignUtil.getVariableMapVal(VariableKeys.FORWARD_VISIABLE, false);
    const showMoreFun = SignUtil.getVariableMapVal(VariableKeys.SHOW_MORE_FUN, false);
    const currOperateType = SignUtil.getVariableMapVal(VariableKeys.CURR_OPERATE_TYPE,{});
    const{ forwardflag } = fowardSubmitParams;
    const resetParams = {};
    resetParams[VariableKeys.FORWARD_VISIABLE] = forwardVisiable;
    resetParams[VariableKeys.SHOW_MORE_FUN] = showMoreFun;
    resetParams[VariableKeys.CURR_OPERATE_TYPE] = currOperateType;
    let forwardflag_back = forwardflag;
    let continuationProcessInfoLoadBak = {...continuationProcessInfo};
    hideContinuationProcessBar();
    hiddenSignInput();
    emClient.editImage({
        'success': (argument) => {
            let result = getEmResultData(argument);
            console.log("editImage result", result);
            const { localData = '' } = result;
            resetContinuationProcessInfo(continuationProcessInfoLoadBak);
            setForwardParams({forwardflag:forwardflag_back})
            saveSignAnnex(2, localData);
            showSignInput(resetParams);
            resetKeyValue();
        },
        'fail': (argument) => {
            resetContinuationProcessInfo(continuationProcessInfoLoadBak);
            showSignInput(resetParams);
            resetKeyValue();
            console.log('editImage-fail', argument);
        },
        'cancel': (argument) => {
            resetContinuationProcessInfo(continuationProcessInfoLoadBak);
            resetKeyValue();
            console.log('editImage-cancel', argument);
        }
    })
}

//录音
export const audioRecord = () => {
    const { saveSignAnnex } = base.allStores.wfSignInputStore;
    emClient.getAudioRecord({
        'success': (argument) => {
            const result = getEmResultData(argument);
            const { localData = '' } = result;
            console.log("audioRecord result :", result);
            saveSignAnnex(1, localData);
        },
        'fail': (argument) => {
            console.log('audioRecord-fail', argument);
        }
    })
}

//位置
export const locationList = (locationdata = {}) => {
    emClient.getLocationList({
        ...locationdata,
        'success': (argument = {}) => {
            let data = argument;
            if (typeof argument == 'string') data = JSON.parse(argument);
            const { isForwad = false, controlVariableMap } = base.allStores.wfSignInputStore;
            const key = isForwad ? VariableKeys.FORWARD_REMARK_LOCATION : VariableKeys.SIGN_REMARK_LOCATION;
            const { title = '', latitude, longitude } = data.result || {};
            if (title !== '') {
                controlVariableMap(key, { latitude, longitude, address: title });
            }
        },
        'fail': (argument) => {
            console.log('editImage-fail', argument);
        }
    })
}

//打开位置
export const openLocation = (params = {}) => {
    emClient.openLocation({
        ...params,
        'scale': 4,
        'success': (argument) => {
            console.log('openLocation-success', argument)
        },
        'fail': (argument) => {
            console.log('openLocation-fail', argument)
        }
    })
}

/**
 * 重置EM客户端生成的对象结构(入口index.js调用)
 */
export const resetEmElement = () => {
    console.log("do resetEmElement ", mobx.toJS(base.wfGlobalStore.variableMap));
    if (judgeApiSupport("resetNavigation")) {
        emClient.ready(function () {
            emClient.resetNavigation({
                'success': function (argument) {
                    console.log('resetEmElement success', JSON.stringify(argument));
                },
                'fail': function (argument) {
                    console.log('resetEmElement fail', JSON.stringify(argument));
                },
                'title': getLabel(500244, "表单详情")
            });
        });
    }
    resetBottomBtn();
    SignUtil.stopPlayingAudio();
}

export const resetBottomBtn = () => {
    if (judgeApiSupport('hideBottomToolBar')) {
        emClient.hideBottomToolBar({
            'success': (argument) => {
                const { controlVariableMap } =  base.allStores.wfSignInputStore;
                controlVariableMap("isShowEmBottomBtn",false)
                console.log('controlHideBottmBtn-success', argument);
            },
            'fail': (argument) => {
                console.log('controlHideBottmBtn-fail', argument);
            }
        });
        
    }
    
   
}

//定制EM表单的头
export const setReqEmTopNav = (pathname, title = "") => {
    const isReq = (pathname === "/req" || pathname === "/req/easyPicture") && window.top.location.href.indexOf("/hoverWindow") === -1;
    const isQYSAuth = pathname === "/req/qysauth";
    const { commonParam={},isCustomUrl='1' } = base.wfGlobalStore;
    const onlyShow = parseInt(commonParam.isviewonly || 0) === 1 || parseInt(commonParam.isaffirmance || 0) === 1;

    let topTitle = getLabel(500244, "表单详情");
    if (title === "") {
        const routeMapTitle = {
            "/req": getPageTitle(),
            "/req/editDetailRow": onlyShow ? getLabel(514566, "查看明细行") : getLabel(500245, "编辑明细行"),
            "/req/picture": getLabel(18912, "流程图"),
            "/req/easyPicture": isCustomUrl=='0'?getLabel(18912, "流程图"):getLabel('82990','自定义地址') ,
            "/req/status": getLabel(386192, "流程状态"),
            "/req/resource": getLabel(386426, "相关资源"),
            "/req/ehOperator": getLabel(500246, "选择操作者"),
            "/req/reject": getLabel(84508, "退回设置"),
            "/req/forwardback": getLabel(388347, "可收回的转发操作"),
            "/req/forward": SignUtil.getForwardTitle(),
            "/req/remark16": getLabel(31025, "选择流程"),
            "/req/remark37": getLabel(390795, "选择文档"),
            "/req/remarkat": getLabel(500247, "选择@对象"),
            "/req/formAnnotationList": getLabel(129658, "全文批注"),
            "/req/soundList": getLabel(128154, "语音"),
            "/req/annexList": getLabel(156, "附件"),
            "/req/secondAuthDetail": getLabel(501209, "数据保护"),
            "/req/secondAuthCert": getLabel(501463, "证书信息"),
            "/req/locationMap": getLabel(502341, "位置轨迹"),
            "/req/remindType": getLabel(504336, "选择提醒方式"),
            "/req/reminderConfirm": getLabel(500902, "请确认提醒接收人"),
            "/req/reminderConfirm/operators": getLabel(504337, "选择提醒接收人"),
            "/req/intervenor": getLabel(501781, "干预设置"),
            "/req/intervenor/Intervenorid": getLabel(504623, "选择干预接收人"),
            "/req/wfFreeFlowSet": "流转设定",
            "/req/qysauth": getLabel(501195, "身份验证"),
            "/req/setting/chuanyueSetting": getLabel( 391412,"接收人设置"),
            "/req/setting/zhuanfaSetting": getLabel( 81768,"接收人权限")
        }
        topTitle = routeMapTitle[pathname];
        //TODO-不直接加载上面的routeMapTitle 的原因是见下面注释
        if (topTitle == null) {
            //表单路由是'req/附件id_uploadadjustment'签字意见附件路由是 '/req/annexList/uploadadjustment'
            if (pathname.indexOf("uploadadjustment") != -1) {
                topTitle = getLabel(506370, "显示调整");
            }
            //理由同上
            if (pathname.indexOf("uploadadjustment/resetname") != -1) {
                topTitle = getLabel(131615, "重命名");
            }
        }
    } else {
        topTitle = title;
    }
    controlEmTopNav({
        title: topTitle,
        left: {
            'name': getLabel(1290, '返回'),
            'action': function (argument) {
                if (isReq && window.location.href.indexOf("/spa/workflow/static4mobileform") > -1) {
                    FormUtil.returnSourcePage({ isReturn: true });
                } else {
                    try {
                        window.historyRoute.go(-1);

                        //契约锁认证，关闭时，做一些特殊的处理
                        if (isQYSAuth) {
                            closeQYSAuth();
                        }
                    } catch (e) {
                        window.close();     //a标签打开超链接情况
                    }
                }
            }
        }
    });
}

/**
 * 控制EM客户端顶部头信息
 */
export const controlEmTopNav = (params = {}) => {
    document.title = params.title ? params.title : "";//和飞信中走此段
    if (!judgeApiSupport("configNavigation")) {
        return;
    }
    const nav = {
        'success': function (argument) {
            console.log('controlEmTopNav success', JSON.stringify(argument));
        },
        'fail': function (argument) {
            console.log('controlEmTopNav fail', JSON.stringify(argument));
        },
        'left': {},
        'title': getLabel(500244, '表单详情'),
        showCloseButton: false
    };
    emClient.ready(function () {
        if (params.title === undefined) {
            params.title = getLabel(500244, '表单详情');
        }
        emClient.configNavigation({ ...nav, ...params });//微信中走此段
    });
}

/**
 * EM点击预览图片队列
 */
export const preViewImage = (params = {}) => {
    if (!judgeApiSupport("previewImage"))
        return;
    const base = {
        'success': function (argument) {
            console.log('preViewImage success', JSON.stringify(argument));
        },
        'fail': function (argument) {
            console.log('preViewImage fail', JSON.stringify(argument));
        },
        'urls': [],
        'current': ''
    };
    emClient.previewImage({ ...base, ...params });
}

//语音转文字
export const speechTotext = () => {
    if (judgeApiSupport('speechTotext')) {
        emClient.speechTotext({
            "speechTotext": function (argument) {
                SignUtil.appendRemark(argument);
            }
        })
    }
}

/**
 *
 * @param argument
 * @return {*}
 */
const getEmResultData = (argument) => {
    let data = argument;
    if (typeof argument == 'string') data = JSON.parse(argument);
    return data;
}


/**
 * 打开新建短信页面 
 */
export const openSendMsg = (requestid) => {
    window.openLink.openSendMsg(requestid)
}

/**
 * 打开新建邮件页面 
 */
export const openSendEmail = (requestid) => {
    window.openLink.openSendEmail(requestid)
}

export const closeWindow = () => {
    if (judgeApiSupport('closeWindow')) {
        emClient.closeWindow();
    }
}